package com.member.common.utils.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.internal.OSSHeaders;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.StorageClass;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Writer;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.oned.Code128Writer;
import com.member.common.config.OSSConfig;
import com.member.common.utils.DateUtils;
import com.member.common.utils.file.FileUtils;
import com.member.common.utils.uuid.IdUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wangxin
 * @Description
 * @date 2024/12/1 13:42
 **/
@Component
public class OSSUtils {

    @Resource
    private OSSConfig ossConfig;


    /**
     * 上传图片 (连接点击可以预览)
     * dugt1998@163.com
     */
    public Map<String, String> uploadImg(MultipartFile file) throws Exception {
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketName = ossConfig.getBucketName();
        String cname = ossConfig.getCname();
        InputStream in = file.getInputStream();
        String fileName = file.getOriginalFilename();
        String extension = null;
        if (fileName != null) {
            extension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        }

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(in.available());
        metadata.setCacheControl("no-cache");
        metadata.setHeader("Access-Control-Allow-Origin", "*");
        metadata.setHeader("Access-Control-Allow-Methods", "POST GET HEAD PUT DELETE");
        metadata.setHeader("Access-Control-Max-Age", "3600");
        metadata.setHeader("Pragma", "no-cache");
        metadata.setContentEncoding("utf-8");
        metadata.setContentType(getContentType(fileName));
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String uuid = IdUtils.fastSimpleUUID();
        String dir = DateUtils.datePath();
        oss.putObject(bucketName, dir + "/" + uuid + extension, in, metadata);
        oss.shutdown();
        in.close();
        String url = cname + dir + "/" + uuid + extension;
        Map<String, String> map = new HashMap<String, String>();
        map.put("path", url);
        map.put("name", uuid + extension);
        return map;
    }
    /**
     * *上传文件，查看
     */
    public Map<String, String> osspdf(MultipartFile file) {
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketName = ossConfig.getBucketName();
        String cname = ossConfig.getCname();
        String fileName = file.getOriginalFilename();
        String contentType = FileUtils.getFileExtension(fileName);
        String ossFileName = IdUtils.fastSimpleUUID() + "." + contentType;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();

            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(bucketName, ossFileName, inputStream);

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS,
                    StorageClass.Standard.toString());

            metadata.setObjectAcl(CannedAccessControlList.PublicReadWrite);
            metadata.setContentType("application/pdf");
            putObjectRequest.setMetadata(metadata);
            ossClient.putObject(putObjectRequest);
            String url = cname + ossFileName;
            Map<String,String> map = new HashMap<String,String>();
            map.put("url", url);
            map.put("fileName", ossFileName);
            map.put("originalFilename", fileName);
            return map;
        } catch (Exception e) {
            throw new RuntimeException();
        } finally {
            ossClient.shutdown();
        }
    }
    public static String getContentType(String FilenameExtension) {
        if (".bmp".equalsIgnoreCase(FilenameExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(FilenameExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(FilenameExtension) ||
                ".jpg".equalsIgnoreCase(FilenameExtension) ||
                ".png".equalsIgnoreCase(FilenameExtension)) {
            return "image/jpg";
        }
        if (".html".equalsIgnoreCase(FilenameExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(FilenameExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.visio";
        }
        if (".pptx".equalsIgnoreCase(FilenameExtension) ||
                ".ppt".equalsIgnoreCase(FilenameExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".docx".equalsIgnoreCase(FilenameExtension) ||
                ".doc".equalsIgnoreCase(FilenameExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(FilenameExtension)) {
            return "text/xml";
        }
        return "image/jpg";
    }


    /**
     * *上传文件，点击返回的地址是下载
     */
    public Map<String, String> ossFileUpload(MultipartFile file) {
        String endpoint = ossConfig.getEndpoint();
        String accessKeyId = ossConfig.getAccessKeyId();
        String accessKeySecret = ossConfig.getAccessKeySecret();
        String bucketName = ossConfig.getBucketName();
        String cname = ossConfig.getCname();
        String fileName = file.getOriginalFilename();
        String contentType = FileUtils.getFileExtension(fileName);
        String ossFileName = IdUtils.fastSimpleUUID() + "." + contentType;
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        try {
            InputStream inputStream = file.getInputStream();

            PutObjectRequest putObjectRequest =
                    new PutObjectRequest(bucketName, ossFileName, inputStream);

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS,
                    StorageClass.Standard.toString());

            metadata.setObjectAcl(CannedAccessControlList.PublicReadWrite);
            metadata.setContentType("application/octet-stream");
            putObjectRequest.setMetadata(metadata);
            ossClient.putObject(putObjectRequest);
            String url = cname + ossFileName;
            Map<String,String> map = new HashMap<String,String>();
            map.put("url", url);
            map.put("fileName", ossFileName);
            map.put("originalFilename", fileName);
            return map;
        } catch (Exception e) {
            throw new RuntimeException();
        } finally {
            ossClient.shutdown();
        }
    }





    public  String generate(String data, int width, int height) throws Exception {
        Writer writer = new Code128Writer();
        // 根据字符串数据生成BitMatrix对象
        BitMatrix bitMatrix = writer.encode(data, BarcodeFormat.CODE_128, width, height);

        // 创建一个BufferedImage对象
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 遍历BitMatrix，根据黑白条纹填充BufferedImage
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());
            }
        }
        MultipartFile multipartFile = fileCase(image);
        Map<String, String> map = this.uploadImg(multipartFile);
        return map.get("path");
    }

    public static MultipartFile fileCase(BufferedImage image) {
        //得到BufferedImage对象
        MultipartFile multipartFile = null;
        try {
            //创建一个ByteArrayOutputStream
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //把BufferedImage写入ByteArrayOutputStream
            ImageIO.write(image, "png", os);
            //ByteArrayOutputStream转成InputStream
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            //InputStream转成MultipartFile
            multipartFile = new MockMultipartFile("file", "file.png", "text/plain", input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return multipartFile;

    }
}
